import Vue from 'vue'
import { AjaxPlugin } from 'vux'
import qs from 'qs';
Vue.use(AjaxPlugin)
Vue.prototype.baseApi = process.env.NODE_ENV === 'production' ? 'http://120.77.207.47:8080' : '/apis/';
const http = Vue.http
http.defaults.timeout = 15000;
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//http.defaults.headers.post['token'] = Vue.prototype.$common.token;
http.defaults.baseURL = Vue.prototype.baseApi;
http.interceptors.request.use(
  config => {
    config.data = config.data || {}
    config.data = qs.stringify(config.data);
    return config;
  },
  error => {
    Vue.$toast.fail('服务器繁忙，请稍后重试！');
    return Promise.reject(error);
  }
);
http.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    switch (error.response && error.response.status) {
      case 401:
        Vue.$toast.fail('请重新登录！');
        this.$common.routerGo("login");
        break;
      default:
        Vue.$toast.fail('服务器繁忙，请稍后重试！');
        break;
    }
    http.CancelToken.source().cancel();
    return Promise.reject(error.response.data);
  }
)
export const base = '';
export const ajax = {
  _fetch: ax => {
    return new Promise((resolve, reject) => {
      http.post(ax.url, ax.params)
        .then(response => {
          const res = response;
          if (!res.success) {
            Vue.$toast.fail(res.msg);
            reject(res);
          }
          resolve(res);
        }, response => {
          reject(response);
        })
        .catch(error => {
          Vue.$toast.fail('服务器繁忙，请稍后重试！');
          reject(error);
        });
    })
  },
  getBigData: ax => {
    return ajax._fetch(ax)
  },
  getMinData: ax => {
    return ajax._fetch(ax)
  },
  postData: ax => {
    let axs = ajax._fetch(ax)
    axs.then(data => {
      let { msg, success } = data;
      if (success) {
        if (ax.msg) {
          if (ax.msg != "hiden")
            Vue.$toast(ax.msg);
        } else
          Vue.$toast(ax.msg);
      }
    })
    return axs
  }

}
